//
//  OAuthViewController.swift
//  sinaweibo
//
//  Created by icefs2 on 15/11/11.
//  Copyright © 2015年 icefs2. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {

    
    //定义一个webview的属性
    
    let webview = UIWebView()
    //参数转移到了tools文件夹下了
    
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fullAccout() {
        let jsstring = "document.getElementById('userId').value = '13651501381' , document.getElementById('passwd').value = 'Aa213213';"
        
        webview.stringByEvaluatingJavaScriptFromString(jsstring)
    }

    override func loadView() {
        view = webview
        
        webview.delegate = self
        
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
         //添加navigationItem的左右2个按钮
        setupUI()
        //加载微博授权网页
        laodoauthweb()
    }
    //登陆后让园圈圈消失
//    override func viewDidDisappear(animated: Bool) {
//        super.viewDidDisappear(animated)
//        SVProgressHUD.dismiss()
//    }
    //添加navigationItem的左右2个按钮
    private func setupUI() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccout")
    }
     //加载微博授权网页
    private func laodoauthweb() {
        let urlstr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + appkey + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlstr)
      let requset = NSURLRequest(URL: url!)
        webview.loadRequest(requset)
        
    }
    
    

}
extension OAuthViewController: UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlstring = request.URL?.absoluteString else {
            return false
        }
        
        if urlstring.hasPrefix("https://api.weibo.com") {
            return true
        }
        if !urlstring.hasPrefix(redirect_uri) {
            return false
        }
        //走到这里必定包含code
        print(urlstring)
        
        guard let query = request.URL?.query else {
            return false
        }
        print(query)
         let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        UserAccoutviewModel().loadToken(code) { (error) -> () in
            print("come here")
            if error != nil {
                SVProgressHUD.showInfoWithStatus(AppErrorTip)
                return
            }
            //授权页面被modal出来的,dismiss不会立即消失
           self.dismissViewControllerAnimated(true, completion: { () -> Void in
            //此处应该发一个通知
            NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "welcome")
           })
            
           
            
            
        }
        return false
    }
   
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
